package core

import (
	"errors"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	//_ "github.com/jinzhu/gorm/dialects/sqlite"
	"strings"
)

type configApp struct {
	Env       string `env:"APP_ENV" default:"prod" yaml:"env"`
	PageSize  int    `env:"APP_PAGE_SIZE" default:"15" yaml:"page_size"`
	HOST      string `env:"APP_HOST" default:"0.0.0.0" yaml:"host"`
	PORT      string `env:"APP_PORT" default:"8080" yaml:"port"`
	SecretKey string `env:"APP_SECRET_KEY" default:"!@#$%^&*" yaml:"secret_key"`
}

type configAdmin struct {
	Username string `env:"AdminUsername" default:"admin" yaml:"username"`
	Password string `env:"AdminPassword" default:"admin123" yaml:"password"`
}

type configDatabase struct {
	Driver   string `env:"DB_Driver" yaml:"driver"`
	Name     string `env:"DB_NAME" yaml:"name"`
	Host     string `env:"DB_HOST" yaml:"host"`
	Port     string `env:"DB_PORT" yaml:"port"`
	User     string `env:"DB_URSET" yaml:"user"`
	Password string `env:"DBPassword" yaml:"password"`
}

type config struct {
	App      configApp      `yaml:"app"`
	Admin    configAdmin    `yaml:"admin"`
	Database configDatabase `yaml:"database"`
}

func (db configDatabase) Connect() (*gorm.DB, error) {
	var connection string
	switch db.Driver {
	case "sqlite3":
		connection = db.Name + ".db"
	case "mysql":
		connection = fmt.Sprintf(
			"%s:%s@%s:%s/%s?charset=utf8&parseTime=True&loc=Local",
			db.User, db.Password, db.Host, db.Port, db.Name,
		)
	case "postgres":
		connection = strings.Join([]string{
			"host=" + db.Host,
			"user=" + db.User,
			"password=" + db.Password,
			"port=" + db.Port,
			"dbname=" + db.Name,
			"sslmode=disable",
		}, " ")
	default:
		return nil, errors.New("unavailable database driver")
	}
	if db, err := gorm.Open(db.Driver, connection); err != nil {
		return nil, err
	} else {
		return db, nil
	}
}
